<template>
  <div class="dialog-main">
    <el-dialog
      v-model="dialogVisible"
      width="50%"
      top="10vh"
      title="新增用户"
      :before-close="handleClose"
      :show-close="false"
      draggable
    >
      <el-tree
        :default-checked-keys="cheackIds"
        ref="treeRef"
        :data="dataList"
        show-checkbox
        node-key="id"
        :props="defaultProps"
        @check="handleCheck"
      />
      <footer class="footer">
        <el-button @click="handleClose" class="btn button">关闭</el-button>
        <el-button class="btn" color="#6C52EA" @click="handleSave">保存</el-button>
      </footer>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { watch, ref, reactive, PropType } from 'vue'
import { ElMessage, ElTree, FormRules } from 'element-plus'
import { getDepartmentList } from '@/apis/organization/department'
import { editUserData } from '@/apis/system/userInfo'
import { IRole, Itype, IUser } from '@/type'
const emit = defineEmits(['dialogClose', 'dialog-add-save'])

const props = defineProps({
  dialog: {
    type: Boolean,
    required: true,
    default: false
  },
  roleDatas: {
    type: Object as PropType<IRole>,
    required: false,
    default: () => {}
  },
  cheackId: {
    type: Array,
    required: true,
    default: () => []
  }
})

const dialogVisible = ref(false)
watch(
  () => props.dialog,
  (newVal) => {
    dialogVisible.value = newVal
  }
)
const roleData = ref<Itype>()
const cheackIds = ref()
const treeRef = ref<InstanceType<typeof ElTree>>()

watch(
  () => [props.roleDatas, props.cheackId],
  (newVal) => {
    ;(roleData.value = newVal[0] as Itype),
      treeRef.value?.setCheckedKeys([]),
      (cheackIds.value = newVal[1])
  },
  { immediate: true }
)

// 新增岗位
const showAddPost = ref(false)
const statusOptions = ref([
  { label: '正常', value: '正常' },
  { label: '待启用', value: '待启用' }
])
const defaultProps = {
  children: 'user_connect',
  label: 'userName'
}
const rules = reactive<FormRules>({
  roleName: [{ required: true, message: '岗位名称不能为空', trigger: 'blur' }],
  department_name: [{ required: true, message: '部门名称不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '部门状态不能为空', trigger: 'blur' }]
})

/**
 * @desc:获取部门岗位数据
 */
interface Tree {
  id: number
  userName: ''
  children: []
  user_connect: []
  department_name: ''
  parent_id: ''
}
const loading = ref(false)
let dataList: Itype = ref()
const getDepartmentData = (data?: string) => {
  loading.value = true
  getDepartmentList()
    .then((res) => {
      if (res) {
        dataList.value = res
        dataList.value.forEach((element: Itype) => {
          element.created_at = new Date(
            +new Date(new Date(element.created_at).toJSON()) + 8 * 3600 * 1000
          )
            .toISOString()
            .replace(/T/g, ' ')
            .replace(/\.[\d]{3}Z/, '')
        })
        let _getName = (data: Tree[]) => {
          for (let i = 0; i < data.length; i++) {
            data[i].userName = data[i].department_name
            if (data[i].children && data[i].children.length) {
              _getName(data[i].children)
            }
          }
          return data
        }
        _getName(dataList.value)
        loading.value = false
      }
      loading.value = false
    })
    .catch(() => {
      ElMessage('服务器内部错误')
    })
}
getDepartmentData()

/**
 * @desc: 点击节点复选框之后触发
 */
const idGroupList = ref<Number[]>([])
const handleCheck = (data: Tree) => {
  let indexId = idGroupList.value.indexOf(data.id)
  if (indexId > -1) {
    idGroupList.value.splice(indexId, 1)
  } else {
    if (data.hasOwnProperty('user_connect')) {
      data.user_connect.forEach((element: IUser) => {
        idGroupList.value.push(element.id)
      })
    } else {
      idGroupList.value.push(data.id)
    }
  }
}

/**
 * 关闭弹窗
 */
const ruleFormRef = ref()
const showAddPosition = ref()
const handleClose = () => {
  dialogVisible.value = false
  emit('dialogClose')
}

/**
 * 部门创建保存
 */
const handleSave = () => {
  // 批量修改role_id
  editUserData(
    {
      role_id: props.roleDatas?.id,
      is_role: 0
    },
    idGroupList.value
  )
    .then((res) => {
      if (res) {
        dialogVisible.value = false
        emit('dialog-add-save')
        ElMessage.success('操作成功！')
      }
    })
    .catch((err) => {
      ElMessage.error('服务器内部错误！')
    })
}
</script>

<style lang="less" scoped>
.btn {
  width: 140px;
  height: 48px;
  opacity: 1;
  border-radius: 4px;
  border: 1px solid rgba(220, 223, 230, 1);
  padding: 15px 61px 15px 61px;
}
:deep(.el-form-item__content) {
  justify-content: center;
}
:deep(.el-dialog) {
  border-radius: 10px;
}
:deep(.el-input) {
  width: 90%;
}
:deep(.el-textarea__inner) {
  width: 90%;
}
.button {
  color: #6c52ea;
}
.button:hover {
  color: #6c52ea;
  border-color: #6c52ea;
  background-color: var(--el-button-hover-bg-color);
  outline: 0;
  opacity: 0.8;
}
.dialog-main {
  .add-form {
    height: 280px;
    overflow-x: hidden;
    overflow-y: auto;
    padding: 0 15%;
    padding-bottom: 10px;
    box-sizing: border-box;
    border-bottom: 1px solid rgba(220, 223, 230, 1);
  }
  .footer {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 80px;
    padding-top: 10px;
    text-align: right;
    .btn {
      width: 150px;
      height: 48px;
      opacity: 1;
      border-radius: 4px;
      border: 1px solid rgba(220, 223, 230, 1);
      display: flex;
      justify-content: flex-start;
      align-items: flex-start;
      padding: 15px 61px 15px 61px;
    }
  }
}
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>
